from .BaseConvert import Convert


class Many2OneConvert(Convert):
    field_type = "many2one"

    @classmethod
    def to_read(cls, rec, field, **kwargs):
        one_type = field.type
        if one_type == 'binary':
            value = {
                'id': rec[field.name].id,
                'name': '/public/image/%s/%s/%s' % (rec[field.name], rec[field.name].id, 'name') if rec['name'] else ''
            }
        else:
            name = rec[field.name]._rec_name
            value = {
                'id': rec[field.name].id or '',
                'name': getattr(rec[field.name], name) if isinstance(getattr(rec[field.name], name), str) else '',
            }

        return value

    @classmethod
    def to_field(cls, value, metadata=None, update=False):
        """
        涉及到many2one的字段，正常传过来的值多为int类型或者布尔类型，所以这里需要进行转换
        """

        if isinstance(value, str):
            value = value.strip()  # 去除字符串前后的空格
            if value.isdigit() and value != '0':  # 字符串是否只由数字组成，只对 0 和 正数有效。
                return int(value)
            if value.lower() in ['0', 'false']:
                return False
        elif isinstance(value, int):
            return value
        elif isinstance(value, bool) and not value:
            return value

    @classmethod
    def to_domain(cls, field, value, **kwargs):
        if not value:
            return []
        else:
            if isinstance(value, str):
                if value.isdigit():
                    return [(field.name, '=', int(value))]
                else:
                    return [(field.name, 'ilike', value)]
            elif isinstance(value, int):
                return [(field.name, '=', value)]
